Page({
  data: {
    groupedImages: [],
    newTitles: {}, // 存放修改后的标题
  },

  onLoad() {
    this.loadImages();
  },

  // 处理标题输入框的内容变化
  onTitleInput(e) {
    const oldTitle = e.currentTarget.dataset.title; // 原标题
    const newTitle = e.detail.value; // 新标题

    let newTitles = this.data.newTitles;
    newTitles[oldTitle] = newTitle; // 存储修改后的标题
    this.setData({
      newTitles: newTitles,
    });
  },

  // 更新标题并移动云存储文件夹
  updateTitle(e) {
    const oldTitle = e.currentTarget.dataset.oldTitle;
    const newTitle = this.data.newTitles[oldTitle] || oldTitle;

    if (newTitle === oldTitle) {
      wx.showToast({
        title: "标题未修改",
        icon: "none",
        duration: 2000,
      });
      return;
    }

    const db = wx.cloud.database();
    const that = this;

    // 查找需要更新的记录
    db.collection("exam-paper-img")
      .where({
        title: oldTitle,
      })
      .get()
      .then((res) => {
        const records = res.data;

        // 遍历每一条记录，逐个更新云存储路径
        const updatePromises = records.map((record) => {
          console.log("新标题:", newTitle);
          const oldFilePath = record.image;
          const newFilePath = `examination-paper/${newTitle}/${new Date().getTime()}_${Math.floor(
            Math.random() * 1000
          )}.jpg`;

          // 先下载云存储文件到本地
          return wx.cloud
            .downloadFile({
              fileID: oldFilePath,
            })
            .then((downloadRes) => {
              const localFilePath = downloadRes.tempFilePath;

              // 然后将文件上传到新路径
              return wx.cloud
                .uploadFile({
                  cloudPath: newFilePath,
                  filePath: localFilePath,
                })
                .then((uploadRes) => {
                  const uploadedFileID = uploadRes.fileID; // 上传成功后返回的文件ID
                  // 删除旧文件
                  return wx.cloud
                    .deleteFile({
                      fileList: [oldFilePath],
                    })
                    .then(() => {
                      // 更新数据库记录
                      return db
                        .collection("exam-paper-img")
                        .doc(record._id)
                        .update({
                          data: {
                            title: newTitle,
                            image: uploadedFileID,
                          },
                        });
                    });
                });
            });
        });

        // 等待所有文件都更新完成
        return Promise.all(updatePromises);
      })
      .then(() => {
        wx.showToast({
          title: "标题修改成功",
          icon: "success",
          duration: 2000,
        });
        that.loadImages(); // 更新数据后重新加载
      })
      .catch((err) => {
        console.error("更新标题和文件夹名失败", err);
        wx.showToast({
          title: "修改失败",
          icon: "none",
          duration: 2000,
        });
      });
  },
  // 审核通过的函数
  approveGroup(e) {
    const title = e.currentTarget.dataset.title; // 获取标题
    const db = wx.cloud.database();
    const that = this;

    // 更新所有对应标题的记录，将 approved 字段设为 true
    db.collection("exam-paper-img")
      .where({
        title: title,
        approved: false,
      })
      .get()
      .then((res) => {
        const records = res.data;
        const approvePromises = records.map((record) => {
          return db
            .collection("exam-paper-img")
            .doc(record._id)
            .update({
              data: {
                approved: true,
              },
            });
        });
        return Promise.all(approvePromises);
      })
      .then(() => {
        wx.showToast({
          title: "审核通过",
          icon: "success",
          duration: 2000,
        });
        that.loadImages(); // 重新加载数据
      })
      .catch((err) => {
        console.error("审核失败", err);
        wx.showToast({
          title: "审核失败",
          icon: "none",
          duration: 2000,
        });
      });
  },
  loadImages() {
    const db = wx.cloud.database();
    db.collection("exam-paper-img")
      .where({
        approved: false, // 筛选未审核的记录
      })
      .get()
      //从数据库中获取数据
      .then((res) => {
        const grouped = this.groupByTitle(res.data);
        this.setData({
          groupedImages: grouped,
        });
        console.log("Grouped Images in Data:", this.data.groupedImages);
      })
      .catch((err) => {
        console.error("加载图片失败", err);
      });
  },

  groupByTitle(records) {
    const grouped = [];
    const titleMap = {};

    records.forEach((record) => {
      const title = record.title || "无标题"; // 如果 title 为空，使用默认值
      if (!titleMap[title]) {
        titleMap[title] = {
          title: title,
          images: [],
        };
        grouped.push(titleMap[title]);
      }
      titleMap[title].images.push(record.image); // 只存储图片的路径
    });

    console.log("Grouped Images:", grouped); // 输出分组结果到控制台
    return grouped;
  },

  previewImage(e) {
    let src = e.currentTarget.dataset.src; // 获取点击图片的云存储路径
    console.log("Cloud Path:", src);

    wx.cloud.getTempFileURL({
      fileList: [src], // 将云存储路径传递给 fileList 数组
      success: (res) => {
        const tempFileURL = res.fileList[0].tempFileURL; // 获取临时URL
        console.log("Temporary URL:", tempFileURL);

        wx.previewImage({
          current: tempFileURL, // 当前显示图片的http链接
          urls: [tempFileURL], // 需要预览的图片http链接列表
        });
      },
      fail: (err) => {
        console.error("获取临时URL失败", err);
      },
    });
  },

  // 删除图片逻辑保持不变
  deleteImage(e) {
    const src = e.currentTarget.dataset.src;
    const title = e.currentTarget.dataset.title;
    let that = this;

    wx.cloud.deleteFile({
      fileList: [src],
      success: (res) => {
        console.log("云存储图片删除成功", res);

        const db = wx.cloud.database();
        db.collection("exam-paper-img")
          .where({
            image: src,
            title: title,
          })
          .remove()
          .then((dbRes) => {
            console.log("数据库记录删除成功", dbRes);
            that.loadImages(); // 重新加载图片
          })
          .catch((err) => {
            console.error("数据库记录删除失败", err);
          });
      },
      fail: (err) => {
        console.error("云存储图片删除失败", err);
      },
    });
  },
  // 保存图片到本地
  saveImage(e) {
    const src = e.currentTarget.dataset.src; // 获取点击图片的云存储路径
    console.log("Saving Image from Cloud Path:", src);

    wx.cloud.getTempFileURL({
      fileList: [src], // 将云存储路径传递给 fileList 数组
      success: (res) => {
        const tempFileURL = res.fileList[0].tempFileURL; // 获取临时URL
        console.log("Temporary URL for Saving:", tempFileURL);

        wx.downloadFile({
          url: tempFileURL,
          success: (downloadRes) => {
            if (downloadRes.statusCode === 200) {
              wx.saveImageToPhotosAlbum({
                filePath: downloadRes.tempFilePath,
                success: () => {
                  wx.showToast({
                    title: "保存成功",
                    icon: "success",
                    duration: 2000,
                  });
                },
                fail: (saveErr) => {
                  console.error("保存图片失败", saveErr);
                  wx.showToast({
                    title: "保存失败",
                    icon: "none",
                    duration: 2000,
                  });
                },
              });
            }
          },
          fail: (downloadErr) => {
            console.error("下载图片失败", downloadErr);
            wx.showToast({
              title: "下载失败",
              icon: "none",
              duration: 2000,
            });
          },
        });
      },
      fail: (err) => {
        console.error("获取临时URL失败", err);
        wx.showToast({
          title: "获取图片失败",
          icon: "none",
          duration: 2000,
        });
      },
    });
  },
});
